package com.gxnu.edu.cn.ttxxt.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gxnu.edu.cn.ttxxt.entity.Messages;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface MessageRepository extends BaseMapper<Messages> {

    @Select("SELECT * FROM messages WHERE sender_id = #{senderId} AND receiver_id = #{receiverId} AND is_group = #{isGroup} ORDER BY send_time DESC")
    List<Messages> findBySenderIdAndReceiverIdAndIsGroup(@Param("senderId") Long senderId,
                                                         @Param("receiverId") Long receiverId,
                                                         @Param("isGroup") Integer isGroup);

    @Select("SELECT * FROM messages WHERE receiver_id = #{receiverId} AND status = #{status} ORDER BY send_time DESC")
    List<Messages> findByReceiverIdAndStatus(@Param("receiverId") Long receiverId,
                                             @Param("status") Integer status);

    @Select("SELECT * FROM messages WHERE " +
            "((sender_id = #{userId} AND receiver_id = #{contactId}) OR " +
            "(sender_id = #{contactId} AND receiver_id = #{userId})) " +
            "ORDER BY send_time DESC " +
            "LIMIT #{size} OFFSET #{offset}")
    List<Messages> findChatHistory(@Param("userId") Long userId,
                                   @Param("contactId") Long contactId,
                                   @Param("isGroup") Integer isGroup,
                                   @Param("offset") int offset,
                                   @Param("size") int size);

    @Update("UPDATE messages SET status = 4, read_time = NOW() " +
            "WHERE receiver_id = #{userId} AND sender_id = #{contactId} AND is_group = #{isGroup} AND status < 4")
    void updateMessagesAsRead(@Param("userId") Long userId,
                              @Param("contactId") Long contactId,
                              @Param("isGroup") Integer isGroup);

    Messages add(Messages messages);
}